package xin.yangshuai.fastjson01.hello;

import com.alibaba.fastjson.serializer.NameFilter;

import java.lang.reflect.Field;

/**
 * MyNameFilter
 *
 * @author shuai
 * @date 2021/3/23
 */
public class MyNameFilter implements NameFilter {

    private String id;

    public MyNameFilter() {
    }

    public MyNameFilter(String id) {
        this.id = id;
    }

    @Override
    public String process(Object o, String name, Object value) {
        try {
            Field field = o.getClass().getDeclaredField(name);
            MyParamName myParamName = field.getDeclaredAnnotation(MyParamName.class);
            NameEle[] nameEles = myParamName.names();
            String defaultName = myParamName.value();
            if (nameEles.length == 0 && defaultName.length() > 0) {
                return defaultName;
            }
            for (NameEle n : nameEles) {
                if (id.equals(n.id())) {
                    return n.value();
                }
            }
        } catch (Exception e) {
            return name;
        }
        return name;
    }
}
